<template>
  <div class="project-board">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="!project" class="empty-state">
      <el-empty description="项目不存在" />
    </div>
    
    <div v-else>
      <!-- 看板头部 -->
      <div class="board-header">
        <div class="header-left">
          <el-button @click="$router.back()">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1>{{ project.name }} - 看板视图</h1>
        </div>
        
        <div class="header-right">
          <el-button type="primary" @click="showCreateTaskDialog = true">
            <el-icon><Plus /></el-icon>
            新建任务
          </el-button>
        </div>
      </div>
      
      <!-- 看板统计 -->
      <div class="board-stats">
        <div class="stat-item">
          <span class="stat-number">{{ stats.total }}</span>
          <span class="stat-label">总任务</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ stats.pending }}</span>
          <span class="stat-label">进行中</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ stats.completed }}</span>
          <span class="stat-label">已完成</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ stats.overdue }}</span>
          <span class="stat-label">已逾期</span>
        </div>
      </div>
      
      <!-- 看板列 -->
      <div class="kanban-board">
        <div class="kanban-column" v-for="column in columns" :key="column.id">
          <div class="column-header">
            <div class="column-title">
              <span class="status-indicator" :class="column.class"></span>
              <span>{{ column.title }}</span>
              <el-badge :value="column.tasks.length" class="task-count" />
            </div>
          </div>
          
          <div class="column-content">
            <div
              v-for="task in column.tasks"
              :key="task.id"
              class="task-card"
              draggable="true"
              @dragstart="handleDragStart(task, column.id)"
              @dragend="handleDragEnd"
            >
              <div class="task-header">
                <h4>{{ task.description }}</h4>
                <el-dropdown @command="(command) => handleTaskAction(command, task)">
                  <el-button type="text" @click.stop>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="edit">编辑任务</el-dropdown-item>
                      <el-dropdown-item command="delete" class="danger">删除任务</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              
              <div class="task-meta">
                <div class="assignee">
                  <el-avatar :size="24">
                    {{ task.assignedToName?.charAt(0) }}
                  </el-avatar>
                  <span>{{ task.assignedToName }}</span>
                </div>
                
                <div class="due-date" :class="{ overdue: isOverdue(task) }">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDate(task.dueDate) }}</span>
                </div>
              </div>
              
              <div v-if="task.actualEndDate" class="completion-info">
                <el-icon><Check /></el-icon>
                <span>完成于 {{ formatDate(task.actualEndDate) }}</span>
              </div>
            </div>
            
            <!-- 拖拽占位符 -->
            <div
              v-if="draggedTask && draggedFromColumn === column.id"
              class="drop-zone"
              @dragover.prevent
              @drop="handleDrop(column.id)"
            >
              <div class="drop-indicator"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      v-model="showCreateTaskDialog"
      :title="editingTask ? '编辑任务' : '新建任务'"
      width="600px"
      @close="resetTaskForm"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="80px"
      >
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="分配给" prop="assignedTo">
          <el-select v-model="taskForm.assignedTo" placeholder="请选择负责人">
            <el-option
              v-for="member in project?.members || []"
              :key="member.userId"
              :label="member.name"
              :value="member.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker
            v-model="taskForm.beginDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
            v-model="taskForm.dueDate"
            type="date"
            placeholder="选择截止日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item v-if="editingTask" label="任务状态">
          <el-select v-model="taskForm.status" placeholder="请选择状态">
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateTaskDialog = false">取消</el-button>
        <el-button type="primary" :loading="taskSubmitting" @click="handleTaskSubmit">
          {{ taskSubmitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getProjectList, type Project } from '@/api/project'
import { getTaskList, createTask, updateTask, deleteTask, type ProjectTask, type CreateTaskRequest, type UpdateTaskRequest } from '@/api/task'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const projectId = computed(() => parseInt(route.params.id as string))

const loading = ref(false)
const taskSubmitting = ref(false)
const showCreateTaskDialog = ref(false)

const project = ref<Project | null>(null)
const tasks = ref<ProjectTask[]>([])
const editingTask = ref<ProjectTask | null>(null)

// 拖拽相关
const draggedTask = ref<ProjectTask | null>(null)
const draggedFromColumn = ref<string>('')

const stats = reactive({
  total: 0,
  pending: 0,
  completed: 0,
  overdue: 0
})

const taskFormRef = ref<FormInstance>()
const taskForm = reactive({
  description: '',
  assignedTo: 0,
  beginDate: '',
  dueDate: '',
  status: 0
})

const taskRules: FormRules = {
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
    { max: 200, message: '任务描述不能超过200个字符', trigger: 'blur' }
  ],
  assignedTo: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  beginDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  dueDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' }
  ]
}

// 看板列配置
const columns = computed(() => [
  {
    id: 'pending',
    title: '进行中',
    class: 'pending',
    tasks: tasks.value.filter(task => task.status === 0)
  },
  {
    id: 'completed',
    title: '已完成',
    class: 'completed',
    tasks: tasks.value.filter(task => task.status === 1)
  }
])

const fetchProject = async () => {
  loading.value = true
  try {
    const result = await getProjectList({
      pageDto: { pageNumber: 1, pageSize: 1 }
    })
    const foundProject = result.data.items.find(p => p.id === projectId.value)
    if (foundProject) {
      project.value = foundProject
    }
  } catch (error) {
    ElMessage.error('获取项目信息失败')
  } finally {
    loading.value = false
  }
}

const fetchTasks = async () => {
  try {
    const result = await getTaskList({
      projectId: projectId.value,
      pageDto: { pageNumber: 1, pageSize: 100 }
    })
    tasks.value = result.data.items
    
    // 计算统计数据
    stats.total = result.data.items.length
    stats.pending = result.data.items.filter(task => task.status === 0).length
    stats.completed = result.data.items.filter(task => task.status === 1).length
    stats.overdue = result.data.items.filter(task => 
      task.status === 0 && dayjs(task.dueDate).isBefore(dayjs())
    ).length
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  }
}

const resetTaskForm = () => {
  editingTask.value = null
  taskForm.description = ''
  taskForm.assignedTo = 0
  taskForm.beginDate = ''
  taskForm.dueDate = ''
  taskForm.status = 0
  taskFormRef.value?.resetFields()
}

const handleTaskAction = async (command: string, task: ProjectTask) => {
  switch (command) {
    case 'edit':
      editingTask.value = task
      taskForm.description = task.description
      taskForm.assignedTo = task.assignedTo
      taskForm.beginDate = task.beginDate
      taskForm.dueDate = task.dueDate
      taskForm.status = task.status
      showCreateTaskDialog.value = true
      break
    case 'delete':
      try {
        await ElMessageBox.confirm('确定要删除这个任务吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteTask(task.id)
        ElMessage.success('删除成功')
        fetchTasks()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

const handleTaskSubmit = async () => {
  if (!taskFormRef.value) return
  
  try {
    const valid = await taskFormRef.value.validate()
    if (!valid) return
    
    taskSubmitting.value = true
    
    if (editingTask.value) {
      const updateData: UpdateTaskRequest = {
        id: editingTask.value.id,
        description: taskForm.description,
        assignedTo: taskForm.assignedTo,
        beginDate: taskForm.beginDate,
        dueDate: taskForm.dueDate,
        status: taskForm.status
      }
      await updateTask(updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateTaskRequest = {
        projectId: projectId.value,
        description: taskForm.description,
        assignedTo: taskForm.assignedTo,
        beginDate: taskForm.beginDate,
        dueDate: taskForm.dueDate
      }
      await createTask(createData)
      ElMessage.success('创建成功')
    }
    
    showCreateTaskDialog.value = false
    fetchTasks()
  } catch (error) {
    ElMessage.error(editingTask.value ? '更新失败' : '创建失败')
  } finally {
    taskSubmitting.value = false
  }
}

// 拖拽处理
const handleDragStart = (task: ProjectTask, columnId: string) => {
  draggedTask.value = task
  draggedFromColumn.value = columnId
}

const handleDragEnd = () => {
  draggedTask.value = null
  draggedFromColumn.value = ''
}

const handleDrop = async (targetColumnId: string) => {
  if (!draggedTask.value || draggedFromColumn.value === targetColumnId) {
    return
  }
  
  const newStatus = targetColumnId === 'completed' ? 1 : 0
  
  try {
    const updateData: UpdateTaskRequest = {
      id: draggedTask.value.id,
      description: draggedTask.value.description,
      assignedTo: draggedTask.value.assignedTo,
      beginDate: draggedTask.value.beginDate,
      dueDate: draggedTask.value.dueDate,
      status: newStatus
    }
    
    await updateTask(updateData)
    ElMessage.success('任务状态已更新')
    fetchTasks()
  } catch (error) {
    ElMessage.error('更新任务状态失败')
  }
}

const isOverdue = (task: ProjectTask) => {
  return task.status === 0 && dayjs(task.dueDate).isBefore(dayjs())
}

const formatDate = (date: string) => {
  return dayjs(date).format('MM-DD')
}

onMounted(() => {
  fetchProject()
  fetchTasks()
})
</script>

<style scoped lang="scss">
.project-board {
  .loading-container {
    padding: 40px 0;
  }
  
  .empty-state {
    padding: 60px 0;
  }
  
  .board-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      h1 {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
    }
  }
  
  .board-stats {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        line-height: 1;
      }
      
      .stat-label {
        color: #666;
        font-size: 14px;
        margin-top: 4px;
      }
    }
  }
  
  .kanban-board {
    display: flex;
    gap: 20px;
    min-height: 600px;
    
    .kanban-column {
      flex: 1;
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      
      .column-header {
        margin-bottom: 16px;
        
        .column-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: bold;
          color: #333;
          
          .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            
            &.pending {
              background-color: #fa8c16;
            }
            
            &.completed {
              background-color: #52c41a;
            }
          }
          
          .task-count {
            margin-left: auto;
          }
        }
      }
      
      .column-content {
        min-height: 500px;
        
        .task-card {
          background: white;
          border-radius: 8px;
          padding: 16px;
          margin-bottom: 12px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          cursor: move;
          transition: all 0.3s;
          
          &:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
          }
          
          .task-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            
            h4 {
              font-size: 14px;
              color: #333;
              margin: 0;
              line-height: 1.4;
              flex: 1;
            }
          }
          
          .task-meta {
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            .assignee {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 12px;
              color: #666;
            }
            
            .due-date {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 12px;
              color: #666;
              
              &.overdue {
                color: #f56c6c;
              }
            }
          }
          
          .completion-info {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: #52c41a;
            margin-top: 8px;
          }
        }
        
        .drop-zone {
          min-height: 100px;
          border: 2px dashed #d9d9d9;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s;
          
          &:hover {
            border-color: #409eff;
            background-color: rgba(64, 158, 255, 0.05);
          }
          
          .drop-indicator {
            width: 100%;
            height: 4px;
            background-color: #409eff;
            border-radius: 2px;
          }
        }
      }
    }
  }
}

:deep(.el-dropdown-menu__item.danger) {
  color: #f56c6c;
  
  &:hover {
    background-color: #fef0f0;
    color: #f56c6c;
  }
}

@media (max-width: 768px) {
  .kanban-board {
    flex-direction: column;
  }
  
  .board-stats {
    flex-wrap: wrap;
    gap: 16px;
  }
}
</style>


